<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="applyTitle">
            <el-input v-model="form.applyTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同签署名称')" prop="contractName">
            <el-input v-model="form.contractName" :placeholder="$t('合同签署名称')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('签约截至时间')" prop="signDate">
            <DatePicker v-model="form.signDate" :placeholder="$t('签约截至时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remake">
            <el-input
              v-model="form.remake"
              type="textarea"
              :rows="8"
              :placeholder="$t('备注')"
              maxlength="2000"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable
        :list.sync="form.fileList"
        data-type="fund_electronic_seals_QY"
        :btn-show="!otherBtnHide"
        file-title="签约文件"
      />

      <FileTable
        :list.sync="form.fileListRelevant"
        data-type="fund_electronic_seals_XG"
        :btn-show="!otherBtnHide"
        file-title="相关文件"
      />

      <div class="mt15">

        <div class="area-header">
          <span class="area-header-title">{{ $t('签约方') }}</span>
        </div>
        <table class="dataTable inline-form">
          <tr>
            <td class="tit">{{ $t('发起模式') }}</td>
            <td>
              <el-form-item prop="launchType">
                <el-radio-group v-model="form.launchType">
                  <el-radio :label="0">{{ $t('单份发起') }}</el-radio>
                  <el-radio :label="1">{{ $t('批量发起') }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </td>
            <td class="tit">{{ $t('签署顺序') }}</td>
            <td>
              <el-form-item prop="launchTorder">
                <el-radio-group v-model="form.launchTorder">
                  <el-radio :label="0">{{ $t('有序发起') }}</el-radio>
                  <el-radio :label="1">{{ $t('无序发起') }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <div class="signed-view">
                <draggable
                  tag="ul"
                  :list="form.fundElectronicPartiesList"
                  class="signed-group"
                  handle=".handle"
                >
                  <li
                    v-for="(item, idx) in form.fundElectronicPartiesList"
                    :key="idx"
                    class="signed-item"
                  >
                    <i class="handle">{{ item.userCompanyType === 2 ? $t('发起方') : $t('接受方') }}</i>
                    <!--"0 企业签约 1个人签约 2 发起方签约" -->
                    <span class="bg">
                      <i class="el-icon-close" @click="removeAt(idx, item.userCompanyType)" />
                      <i class="close" />
                    </span>

                    <!-- 发起方 -->
                    <div v-if="item.userCompanyType === 2 " class="view">
                      <el-row>
                        <el-col :span="12">
                          <el-form-item :label="$t('业务类型')" :prop="'fundElectronicPartiesList.' + idx + '.signTypeId'" :rules="fundElectronicPartiesListRules.signTypeId">
                            <dictSelect
                              v-model="item.signTypeId"
                              :clearable="true"
                              dictionary="subject_type"
                              @change="signTypeChange(idx)"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item :label="$t('用印主体')" :prop="'fundElectronicPartiesList.' + idx + '.signNameId'" :rules="fundElectronicPartiesListRules.signNameId">
                            <MainBodySelect v-model="item.signNameId" :parameters="item.signTypeId" @change="getSigners(item.signNameId, false)" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item :label="$t('签约主体')" :prop="'fundElectronicPartiesList.' + idx + '.signSubject'" :rules="fundElectronicPartiesListRules.signSubject">
                            <el-input v-model="item.signSubject" disabled />
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <span v-show="item.show" class="ps" style="display: block;line-height: 3.5;">{{ $t('提示：未关联签约主体，请联系管理员') }}</span>
                        </el-col>
                        <el-col :span="10" />
                        <el-col :span="24">
                          <el-form-item :label="$t('使用印章')" :prop="'fundElectronicPartiesList.' + idx + '.signSealId'" :rules="fundElectronicPartiesListRules.signSealId">
                            <el-checkbox-group v-model="item.signSealId">
                              <el-checkbox
                                v-for="(useSeal) in item.lists"
                                :key="useSeal.id"
                                :label="useSeal.id"
                              >
                                <el-popover trigger="hover" placement="top-start" width="200">
                                  <el-image :src="useSeal.url" />
                                  <span slot="reference">{{ useSeal.name }}</span>
                                </el-popover>
                              </el-checkbox>
                            </el-checkbox-group>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </div>

                    <div v-if="item.userCompanyType === 0" class="view">
                      <el-row>
                        <el-col :span="12">
                          <el-form-item :label="$t('企业名称')" :prop="'fundElectronicPartiesList.'+ idx +'.signCompanyName'" :rules="fundElectronicPartiesListRules.signCompanyName">
                            <el-input v-model="item.signCompanyName" size="small" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item :label="$t('经办人')" :prop="'fundElectronicPartiesList.'+ idx +'.signUser'" :rules="fundElectronicPartiesListRules.signUser">
                            <!-- 签署要求 字典（0 经办人 1法定代表人 2企业签章-->
                            <div style="display: flex;column-gap: 10px;">
                              <el-input v-model="item.signUser" size="small" :placeholder="$t('接收人真实姓名')" />
                            </div>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item :label="$t('联系方式')" :prop="'fundElectronicPartiesList.'+ idx +'.signUserContact'" :rules="fundElectronicPartiesListRules.signUserContact">
                            <div style="display: flex;column-gap: 10px;">
                              <el-input v-model="item.signUserContact" size="small" :placeholder="$t('接收人手机号/邮箱')" />
                            </div>
                          </el-form-item>
                        </el-col>
                        <el-col :span="24">
                          <el-form-item :label="$t('签署要求')" :prop="'fundElectronicPartiesList.'+ idx +'.signRequirement'" :rules="fundElectronicPartiesListRules.signRequirement">
                            <el-checkbox-group v-model="item.signRequirement">
                              <el-checkbox label="0">{{ $t('经办人') }}</el-checkbox>
                              <el-checkbox label="1">{{ $t('法人') }}</el-checkbox>
                              <el-checkbox label="2">{{ $t('企业签章') }}</el-checkbox>
                            </el-checkbox-group>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </div>
                    <div v-if="item.userCompanyType === 1 " class="view">
                      <el-row>
                        <el-col :span="12">
                          <el-form-item :label="$t('个人姓名')" :prop="'fundElectronicPartiesList.'+ idx +'.signUser'" :rules="fundElectronicPartiesListRules.signUser">
                            <div style="display: flex;column-gap: 10px;">
                              <el-input v-model="item.signUser" size="small" :placeholder="$t('接收人真实姓名')" />
                            </div>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item :label="$t('联系方式')" :prop="'fundElectronicPartiesList.'+ idx +'.signUserContact'" :rules="fundElectronicPartiesListRules.signUserContact">
                            <div style="display: flex;column-gap: 10px;">
                              <el-input v-model="item.signUserContact" size="small" :placeholder="$t('接收人手机号/邮箱')" />
                            </div>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </div>
                  </li>
                </draggable>
              </div>
            </td>
          </tr>

          <tr>
            <td colspan="4">
              <a v-if="isLaunch" class="link_a mr5" @click="addInitiator(2)">{{ $t('添加发起方') }}</a>
              <a class="link_a mr5" @click="addEnterprise()">{{ $t('添加企业') }}</a>
              <a class="link_a mr5" @click="addPersonal()">{{ $t('添加个人') }}</a>
              <a v-if="showInvestor" class="link_a mr5" @click="addPayPersons()">{{ $t('批量选择出资人') }}</a>
            </td>
          </tr>
        </table>
      </div>
    </el-form>
    <!--  id="anchor"   -->
    <div slot="footer" class="dialog-footer" style="text-align: right;margin-top: 10px">
      <FormBtn ref="formBtn" has-permi="fund:contract" :bus-data="form" :btn-hide="btnHide" />
    </div>

    <!-- 模态框，绑定table.-->
    <el-dialog
      :visible.sync="fundTableFormOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      custom-class="dialogForm"
      append-to-body
    >
      <fundInverstorTable
        ref="fundInverstorTable"
        @closeInvestPage="closeInvestPage"
        @addPersonInvest="addPersonInvest"
        @addEnterpriseInvest="addEnterpriseInvest"
        @deleteRowData="deleteRowData"
      />
    </el-dialog>

  </div>
</template>

<script>
import { saveFundElectronicSeals, getFundElectronicSeals } from '@/api/fund/contract/fundElectronicSeals'
import { getSealByCompanyName, getSealInfoByInvestId } from '@/api/oa/maintain/oaElectronicSignatureMaintain'
import draggable from 'vuedraggable'
import MainBodySelect from '@/components/MainBodySelect'
import fundInverstorTable from './fundInverstorTable'

export default {
  name: 'FundElectronicSealsForm',
  components: {
    draggable,
    MainBodySelect,
    fundInverstorTable
  },
  data() {
    // 自定义校验规则
    var checkMobilOrPhone = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
      const regMobile = /^1\d{10}$/
      if (regEmail.test(value)) {
        this.$set(this.form.fundElectronicPartiesList, 'contactType', 'MOBILE')
        return callback()
      } else if (regMobile.test(value)) {
        this.$set(this.form.fundElectronicPartiesList, 'contactType', 'EMAIL')
        return callback()
      }
      callback(new Error(this.$t('请输入合法的邮箱或手机号!')))
    }

    return {
      // 是否隐藏保存按钮
      btnHide: false,
      formOpen: false,
      fundTableFormOpen: false,
      // 是否隐藏其它按钮
      otherBtnHide: false,
      // 表单参数
      form: {
        contractName: undefined,
        // 附件列表
        fileList: [],
        fileListRelevant: [],
        fundElectronicPartiesList: [
          {
            userCompanyType: 2,
            signSealId: [],
            piles: '',
            lists: [],
            signTypeId: 'fund',
            signNameId: '',
            signSubject: '',
            launchTorder: '',
            show: false,
            signCompanyName: '',
            signRequirement: [],
            signUser: '',
            signUserContact: '',
            contactType: '',
            subjectType: '',
            subjectName: ''
          }
        ]
      },
      rules: {
        contractName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        applyTitle: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        signDate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        fileList: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        launchType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        launchTorder: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      fundElectronicPartiesListRules: {
        signSubject: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        signUserContact: [{ required: true, validator: checkMobilOrPhone, message: this.$t('手机号或者邮箱不正确'), trigger: 'blur' }],
        signUser: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        signCompanyName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        signRequirement: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        signTypeId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        signNameId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        signSealId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }]
      },
      loading: false,
      options: [],
      isLaunch: false,
      // 出资人展示
      showInvestor: false
    }
  },
  watch: {
    'form.fundElectronicPartiesList': {
      handler(val) {
        if (val) {
          this.form.fundElectronicPartiesList.forEach(item => {
            if (item.userCompanyType === 2) {
              if (item.signTypeId === 'fund' && item.signNameId !== undefined && item.signNameId !== null && item.signNameId !== '') {
                this.showInvestor = true
              } else {
                this.showInvestor = false
              }
            }
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
  },
  mounted() {
    this.$bus.$emit('async_done')
  },
  methods: {
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getFundElectronicSeals(data.id).then(response => {
          this.form = response.data
          this.getSigners(this.form.fundId, true)
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        contractName: undefined,
        fundId: undefined,
        signDate: undefined,
        remark: undefined,
        fileList: [],
        fileListRelevant: [],
        launchType: 0,
        launchTorder: 0,
        fundElectronicPartiesList: [{
          userCompanyType: 2,
          signSealId: [],
          signTypeId: 'fund',
          signNameId: '',
          signSubject: '',
          show: false,
          signCompanyName: '',
          signRequirement: [],
          signUser: '',
          signUserContact: '',
          subjectType: '',
          subjectName: '',
          list: []
        }],
        payPersonList: [{
          type: '',
          userName: '',
          phone: '',
          email: ''
        }]
      }
      this.resetForm('form')
    },

    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.reset()
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    submitForm(type) {
      this.$refs['form'].validate(valid => {
        var isFile = this.form.fileList !== undefined && this.form.fileList !== null && this.form.fileList.length > 0
        if (!isFile) {
          this.msgError(this.$t('请上传签约文件!'))
        }
        // 验证数据
        if (valid && isFile) {
          // 弹出遮罩层
          this.loading = true
          // 保存数据
          saveFundElectronicSeals(this.form).then(response => {
            if (response.code === 200) {
              // 点击的按钮是保存并启动流程
              if (type === 'process') {
                // 启动流程
                this.startProcess(response.data.id)
                // 点击的仅保存
              } else {
                this.msgSuccess(this.$t('保存成功'))
                // 关闭form页面
                this.closeForm()
              }
            } else {
              this.msgError(response.msg)
              this.loading = false
            }
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 启动流程
    startProcess(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.applyTitle
      // 业务表名
      processData.dataTable = 'fund_electronic_seals'
      // 业务ID 根据 业务表名 和 业务ID 俩个字段来更新流程的审批状态和流程实例ID
      processData.dataId = dataId
      // 业务表单地址 待办时查看的页面
      processData.formPath = '@/views/fund/contract/fundElectronicSealsForm'
      // 业务表单打印地址
      processData.viewPath = '@/views/fund/contract/fundElectronicSealsForm'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = 'fund_electronic_seals'
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    /**
     * 业务类型改变时 清空印章及公司名称
     * @param index
     */
    signTypeChange(index) {
      var object = this.form.fundElectronicPartiesList[index]
      object.signNameId = undefined
      object.show = true
      object.lists = []
      object.signSealId = []
      object.signSubject = undefined
    },
    /**
     * 获取签署人员
     * @param fundId 选择的主体ID
     * @param isInit 是否是初次加载. 如果是的话不能清理掉 选中的印章
     */
    getSigners(fundId, isInit) {
      this.form.fundId = fundId
      const fundElectronicPartiesList = this.form.fundElectronicPartiesList
      if (fundElectronicPartiesList !== undefined && fundElectronicPartiesList !== null) {
        fundElectronicPartiesList.forEach(item => {
          // 获取发起方
          if (item.userCompanyType === 2) {
            item.signNameId = this.form.fundId
            // 根据当前主体获取绑定的公司名称
            getSealInfoByInvestId(item.signNameId).then(response => {
              console.log(response)
              item.lists = []
              if (!isInit) {
                item.signSealId = []
              }
              if (response.data !== null) {
                item.signSubject = response.data.companyName
                item.show = false
                // 获取当前基金绑定的公司印章
                getSealByCompanyName(response.data.companyName).then(response => {
                  item.lists = response.data
                  // 刷新双向绑定
                  this.$forceUpdate()
                })
              } else {
                item.show = true
                item.signSubject = undefined
              }
            })
          }
        })
      }
    },
    /**
     * 添加发起方
     * @param userCompanyType
     */
    addInitiator(userCompanyType) {
      var row = {
        name: '',
        signTypeId: '',
        signNameId: '',
        signSubject: '',
        signSealId: '',
        userCompanyType: userCompanyType
      }
      this.form.fundElectronicPartiesList.push(row)
      this.isLaunch = false
      this.goAnchor()
    },
    /** 批量选择出资人 */
    addPayPersons() {
      // 调用fundInfoTable 弹出框列表
      this.fundTableFormOpen = true
      this.$nextTick(() => {
        this.$refs.fundInverstorTable.init(this.form.fundId, this.form.fundElectronicPartiesList)
      })
    },
    closeInvestPage() {
      this.fundTableFormOpen = false
    },
    // 来自出资人页面选择的个人
    addPersonInvest(tempId, userName, phone) {
      // 判断页面上是否有这行数据. 存在则不添加
      if (!this.form.fundElectronicPartiesList.find(obj => obj.tempId === tempId)) {
        this.addPersonal(tempId, userName, phone)
      }
    },
    // 来自出资人选择 企业
    addEnterpriseInvest(tempId, companyName, userName, phone) {
      // 判断页面上是否有这行数据. 存在则不添加
      if (!this.form.fundElectronicPartiesList.find(obj => obj.tempId === tempId)) {
        this.addEnterprise(tempId, companyName, userName, phone)
      }
    },
    // 出资人选择. 第二次选择时, 清理掉删选的行
    deleteRowData(data) {
      console.log('清理的行', data)
      if (this.form.fundElectronicPartiesList && data && data.length > 0) {
        this.form.fundElectronicPartiesList.forEach((item, index) => {
          if (data.includes(item.tempId) && item.tempId !== undefined) {
            this.form.fundElectronicPartiesList.splice(index, 1)
          }
        })
      }
    },
    /** 添加企业*/
    addEnterprise(tempId, signCompanyName, signUser, signUserContact) {
      const row = {
        tempId: tempId,
        signCompanyName: signCompanyName,
        signUser: signUser,
        signUserContact: signUserContact,
        signRequirement: ['2'],
        signSealId: [],
        contactType: '',
        userCompanyType: 0
      }
      this.form.fundElectronicPartiesList.push(row)
      this.goAnchor()
    },
    /** 添加个人 */
    addPersonal(tempId, signUser, signUserContact) {
      const row = {
        tempId: tempId,
        signUser: signUser,
        contactType: undefined,
        signUserContact: signUserContact,
        userCompanyType: 1
      }
      this.form.fundElectronicPartiesList.push(row)
      this.goAnchor()
    },
    /**
     * 删除某个出资人 发起方 或是 企业
     * @param idx
     * @param type
     */
    removeAt(idx, type) {
      this.form.fundElectronicPartiesList.splice(idx, 1)
      if (type === 2) {
        this.isLaunch = true
      }
    },
    /**
     * 页面宽度调整
     */
    goAnchor() {
      this.$nextTick(() => {
        var container = this.$el.querySelector('.el-form')
        container.scrollTop = container.scrollHeight
      })
    }

  }
}
</script>
